<!-- 消耗计量 -->
<template>
  <div class="energy_consume">
    <div class="content-left">
      <div class="tree-search">
        <px-input v-model="treeSearchVal" placeholder="请输入" :prefix-icon="Search" />
      </div>
      <div class="tree-bar">
        <px-scrollbar>
          <px-tree
            ref="treeRef"
            :data="treeData"
            node-key="id"
            :default-expanded-keys="defaultExpandedKeys"
            highlight-current
            :filter-node-method="filterNode"
            :current-node-key="currentNode"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          >
            <template #default="{ data }">
              <px-tooltip :content="data.label" placement="top" :show-after="showAfter">
                <span :style="data.disabled ? { cursor: 'not-allowed', userSelect: 'none' } : ''">
                  {{ data.label }}
                </span>
              </px-tooltip>
            </template>
          </px-tree>
        </px-scrollbar>
      </div>
    </div>
    <div class="content-right">
      <div :class="['top_query', showContent === '1' ? 'pd1624024' : 'pd1624']">
        <px-form ref="queryRef" class="custom-form-ui inspection-form" :model="queryParams" :inline="true" label-width="100px">
          <px-form-item label="时间维度" prop="dataFormat" style="width: auto; padding-right: 10px">
            <px-radio-group v-model="queryParams.queryTimeGranularity" style="margin-left: 10px" @change="handleChangeFn">
              <!-- <px-radio size="small" label="Hourly">小时</px-radio> -->
              <px-radio size="small" label="Daily">日</px-radio>
              <px-radio size="small" label="Monthly">月</px-radio>
              <px-radio size="small" label="Yearly">年</px-radio>
            </px-radio-group>
          </px-form-item>
          <px-form-item label="时间范围" style="width: 380px">
            <!-- <px-time-picker
            v-if="queryParams.queryTimeGranularity === 'Hourly'"
            v-model="dateRange"
            is-range
            range-separator="-"
            format="HH"
            value-format="HH"
            start-placeholder="开始小时"
            end-placeholder="结束小时"
          /> -->
            <px-date-picker
              v-if="queryParams.queryTimeGranularity === 'Daily'"
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :clearable="false"
              @change="changeFnDay"
            />
            <px-date-picker
              v-if="queryParams.queryTimeGranularity === 'Monthly'"
              v-model="dateRange"
              type="monthrange"
              value-format="YYYY-MM"
              range-separator="-"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              :clearable="false"
              @change="changeFnMonth"
            />
            <div v-if="queryParams.queryTimeGranularity === 'Yearly'">
              <yearPicker
                ref="statisticPicker"
                :labelWidth="0"
                labelText=""
                :clearable="false"
                :initYear="dateValue"
                @updateTimeRange="updateStatisticYear"
              />
            </div>
          </px-form-item>
          <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
          <px-button icon="" @click="resetQuery">重置</px-button>
        </px-form>
        <div v-if="showContent === '1'" class="top-wrap">
          <px-radio-group v-model="activeName" class="tabSwitch">
            <px-radio v-for="item in tabsOption" :key="item.name" size="small" :label="item.label">{{ item.name }}</px-radio>
          </px-radio-group>
        </div>
      </div>
      <div v-if="showContent === '1'" class="content">
        <switchTableTabs
          :key="currentNode + switchTableTabsKey"
          :currentNode="currentNode"
          :queryParams="queryParams"
          :currentSystem="currentSystem"
          :activeName="activeName"
        />
      </div>
      <div v-if="showContent === '2'" class="content">
        <systemChartTable
          :key="currentNode + switchTableTabsKey"
          :currentNode="currentNode"
          :queryParams="queryParams"
          :currentSystem="currentSystem"
        />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance, onMounted, nextTick, reactive, toRefs, watch } from "vue";
import yearPicker from "@/views/common/energy/components/yearPicker.vue";
import switchTableTabs from "./switchTableTabs/index.vue";
import systemChartTable from "./systemChartTable/index.vue";
import { PxMessage } from "px-ui";
import { Search } from "@px-ui/icons-vue";
import dayjs from "dayjs";
import { getLoadConsumeSystemTreeApi } from "@/api/energy/common";

defineOptions({
  name: "ALL_ENERGY_CONSUME_MEASUREMENT"
});

const isLeaf = ref(false);

const { proxy } = getCurrentInstance();

const yearStart = ref("");
const yearEnd = ref("");
const switchTableTabsKey = ref(new Date().getTime());
// 可选择区间，initYear传参，不传则所有年份有效，小于0判断一下？
const dateValue = ref({
  startYear: `${new Date().getFullYear() - 2}`,
  endYear: `${new Date().getFullYear()}`
});

const showContent = ref("1"); // 1: 前端写的组件，2：帆软，3：暂无数据
const state = reactive({
  treeSearchVal: "",
  treeData: [],
  currentNode: "0",
  showAfter: 1000,
  currentSystem: "厂务系统", // 当前点击的系统,默认厂务系统
  defaultExpandedKeys: [],
  activeName: "all" // 默认总能耗折标煤
});
const { treeSearchVal, treeData, currentNode, showAfter, currentSystem, defaultExpandedKeys, activeName } = toRefs(state);

const tabsOption = [
  {
    label: "all",
    name: "总能耗折标煤",
    flag: "2"
  },
  {
    label: "electricity",
    name: "电",
    flag: "1"
  },
  {
    label: "running",
    name: "水",
    flag: "3"
  },
  {
    label: "reclaim",
    name: "再生水",
    flag: "4"
  },
  {
    label: "ng",
    name: "天然气",
    flag: "5"
  },
  {
    label: "hotSteam",
    name: "蒸汽/热水",
    flag: "9"
  },
  {
    label: "gas",
    name: "大宗气",
    flag: "8"
  }
];

const treeRef = ref();

watch(treeSearchVal, val => {
  treeRef.value.filter(val);
});

// 过滤树数据
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.includes(value);
};

// 递归函数，用于给叶子节点添加属性
const addPropertyToLeafNodes = (node, args) => {
  if (!node?.children || node?.children?.length === 0) {
    // 是叶子节点，添加属性
    node.disabled = false;
    node.flag = args;
  } else {
    node.flag = args;
    // 不是叶子节点，递归遍历子节点
    node.children.forEach(child => {
      addPropertyToLeafNodes(child, args);
    });
  }
  return node;
};

// 拼接数据
const getTreeData = async () => {
  try {
    const params = {
      code: "summary"
    };
    const res = await getLoadConsumeSystemTreeApi(params);
    if (res?.length) {
      res[0].flag = "quanchang";
      res[0]?.children?.forEach(i => {
        let flag = i?.id;
        addPropertyToLeafNodes(i, flag);
      });
      let resAry = res;
      state.treeData = resAry;
      state.defaultExpandedKeys = findDefaultExpandedKeys(resAry);
      nextTick(() => {
        state.currentNode = resAry[0].children[0].id;
        treeRef.value?.setCurrentKey([resAry[0].children[0].id]);
        showContent.value = "1";
      });
    }
  } catch (error) {}
};

// 扁平化树结构并标记叶子节点
const flattenAndMarkLeaves = nodes => {
  const nodeMap = new Map();

  const traverse = (items, parentId = null) => {
    items.forEach(node => {
      const isLeaf = !node.children || node.children.length === 0;
      nodeMap.set(node.id, { ...node, isLeaf, parentId });

      if (!isLeaf) {
        traverse(node.children, node.id);
      }
    });
  };
  traverse(nodes);
  return nodeMap;
};

// 找到默认打开的key
const findDefaultExpandedKeys = nodes => {
  // 扁平化树并标记叶子节点
  const nodeMap = flattenAndMarkLeaves(nodes);
  const grandparentIds = new Set();

  // 遍历所有节点，收集叶子节点的爷爷节点ID
  for (const [id, node] of nodeMap.entries()) {
    if (node.isLeaf) {
      const parentId = node.parentId;
      const parentNode = nodeMap.get(parentId);

      if (parentNode) {
        const grandparentId = parentNode.parentId;
        if (grandparentId !== null && grandparentId !== undefined) {
          grandparentIds.add(grandparentId);
        }
      }
    }
  }

  // 设置默认展开的节点
  return Array.from(grandparentIds);
};

// 点击的处理方法
const handleNodeClick = (data, node) => {
  state.currentSystem = data?.label;
  // 全场
  if (data?.flag === "quanchang") {
    showContent.value = "1";
    isLeaf.value = node.isLeaf;
    state.currentNode = data.id || encodeURIComponent(data.label);
    state.activeName = "all";
  }
  // 厂务侧,
  // 叶子节点不显示，不能点击
  // 其他节点用前端写的组件
  if (data?.flag === "fac") {
    // 叶子节点
    if (data?.children?.length) {
      showContent.value = "1";
      state.activeName = "all";
    } else {
      showContent.value = "2";
    }
    isLeaf.value = node.isLeaf;
    state.currentNode = data.id || encodeURIComponent(data.label);
  }
  // 机台侧，
  // 叶子节点不显示右侧的内容，
  // 其他节点用前端写的组件
  if (data?.flag === "fab") {
    // 叶子节点
    if (data?.children?.length) {
      showContent.value = "1";
      state.activeName = "all";
    } else {
      showContent.value = "2";
    }
    isLeaf.value = node.isLeaf;
    state.currentNode = data.id || encodeURIComponent(data.label);
  }
  // 其他侧，
  // 叶子节点不显示右侧的内容,
  // 其他节点用前端写的组件
  if (data?.flag === "other") {
    // 叶子节点不显示右侧的内容
    if (data?.children?.length) {
      showContent.value = "1";
      state.activeName = "all";
    } else {
      showContent.value = "2";
    }
    isLeaf.value = node.isLeaf;
    state.currentNode = data.id || encodeURIComponent(data.label);
  }
};

// 定义数据
const dateRange = ref([]);

const queryParams = ref({
  queryTimeGranularity: "Monthly",
  factory: ""
});

// 获取当月第一天
const getCurrentMonthF = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m = date.getMonth() + 1; // 获取月
  let d = "01";
  m = m < 10 ? "0" + m : m;
  return [y, m, d].join("-");
};

// 获取当月最后一天
const getCurrentMonthL = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m = date.getMonth() + 1; // 获取月
  let d = new Date(y, m, 0).getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return [y, m, d].join("-");
};

// 校验时间范围不为空
const checkDate = () => {
  if (queryParams.value.queryTimeGranularity) {
    if (dateRange.value && dateRange.value.length) {
      return true;
    }
    if (queryParams.value.startTime && queryParams.value.endTime) {
      return true;
    }
  }
};

// 获取某月最后一天
const getMonthLastDay = (y, m) => {
  let date = new Date(y, m - 1, "01");
  date.setDate(1);
  date.setMonth(date.getMonth() + 1);
  let cdate = new Date(date.getTime() - 1000 * 60 * 60 * 24);
  return cdate.getDate();
};

const timeType = ref("Monthly");
/** 搜索按钮操作 */
function handleQuery() {
  timeType.value = queryParams.value.queryTimeGranularity;
  // if (!queryParams.value.factory) {
  //   console.log("没有厂区");
  //   return;
  // }
  if (queryParams.value.queryTimeGranularity === "Daily") {
    queryParams.value.startTime = dateRange.value[0] + " 00:00:00";
    queryParams.value.endTime = dateRange.value[1] + " 23:59:59";
  } else if (queryParams.value.queryTimeGranularity === "Monthly") {
    queryParams.value.startTime = dateRange.value[0].indexOf("00") != -1 ? dateRange.value[0] : dateRange.value[0] + "-01 00:00:00";
    const d = getMonthLastDay(Number(dateRange.value[1].split("-")[0]), Number(dateRange.value[1].split("-")[1]));
    queryParams.value.endTime = dateRange.value[1].indexOf("59") != -1 ? dateRange.value[1] : dateRange.value[1] + "-" + d + " 23:59:59";
  } else if (queryParams.value.queryTimeGranularity === "Hourly") {
    //获取新的时间
    let date = new Date();
    //获取当前时间的年份转为字符串
    let year = date.getFullYear().toString();
    //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
    let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
    //获取天，判断是否小于10，如果是在字符串前面拼接'0'
    let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
    queryParams.value.startTime = `${year}-${month}-${da} ${dateRange.value[0]}:00:00`;
    queryParams.value.endTime = `${year}-${month}-${da} ${dateRange.value[1]}:59:59`;
  } else {
    queryParams.value.startTime = yearStart.value;
    queryParams.value.endTime = yearEnd.value;
  }
  switchTableTabsKey.value = new Date().getTime(); // 刷新组件
  proxy.$refs["queryRef"].validate(valid => {
    if (!valid) return;
    if (queryParams.value.queryTimeGranularity) {
      if (!checkDate()) {
        return PxMessage({
          type: "warning",
          message: "时间范围不能为空"
        });
      }
    }
  });
}
const handleChangeFn = val => {
  //获取新的时间
  let date = new Date();
  //获取当前时间的年份转为字符串
  let year = date.getFullYear().toString();
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let y = date.getFullYear(); // 获取年
  let m = date.getMonth() + 1; // 获取月
  switch (val) {
    case "Hourly":
      dateRange.value = ["00", "23"];
      break;
    case "Daily":
      dateRange.value = [getCurrentMonthF(), getCurrentMonthL()];
      break;
    case "Monthly":
      dateRange.value = [`${year}-${month}`, `${year}-${month}`];
      break;
    case "Yearly":
      let yearE = new Date().getFullYear();
      yearStart.value = `${yearE - 2}-01-01 00:00:00`;
      yearEnd.value = `${yearE}-12-31 23:59:59`;
      break;
    default:
      break;
  }
  // 刷新页面
  handleQuery();
};
/** 重置按钮操作 */
function resetQuery() {
  initQuery();
  // 默认执行一下
  handleQuery();
}
const changeFnDay = () => {
  // 刷新页面
  handleQuery();
};
const changeFnMonth = () => {
  // 刷新页面
  handleQuery();
};

// 选完/输入完成的回调
const updateStatisticYear = (startYear, endYear) => {
  dateRange.value = [startYear ? startYear.toString() : "", endYear ? endYear.toString() : ""];
  yearStart.value = `${startYear}-01-01 00:00:00`;
  yearEnd.value = `${endYear}-12-31 23:59:59`;
  // 刷新页面
  handleQuery();
};

// 默认查询条件
const initQuery = () => {
  queryParams.value.queryTimeGranularity = "Monthly";
  timeType.value = "Monthly";
  dateRange.value = [dayjs().subtract(12, "month").format("YYYY-MM"), dayjs().subtract(1, "month").format("YYYY-MM")];
  queryParams.value.startTime = dayjs().subtract(12, "month").format("YYYY-MM") + "-01 00:00:00";
  queryParams.value.endTime = dayjs().subtract(1, "month").endOf("month").format("YYYY-MM-DD") + " 23:59:59";
};

onMounted(() => {
  getTreeData();
  initQuery();
});
</script>

<style lang="scss" scoped>
.energy_consume {
  box-sizing: border-box;
  display: flex;
  align-items: center;

  .top_turnback {
    margin-bottom: 16px;
  }

  .pd1624 {
    padding: 16px 24px;
  }

  .pd1624024 {
    padding: 16px 24px 0;
  }

  .top_query {
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    width: 100%;
    height: auto;
    margin-bottom: 16px;
    line-height: 44px;
    background: #fff;
    border-radius: 4px;

    .query_top {
      display: flex;

      /*
      * tab样式
      */
      .tabSwitch {
        min-width: 200px;
        padding: 0 5px;
        margin-right: 20px;
        background-color: #f4f4f4;
        border-radius: 4px;

        :deep(.px-radio-button__inner) {
          background-color: #f4f4f4;
          border: none;
        }

        :deep(.is-active) {
          border: none;

          .px-radio-button__inner {
            background-color: var(--px-color-primary);
            border-radius: 4px;
          }
        }
      }
    }

    .select_year {
      display: flex;
      align-items: center;
      justify-content: left;
      margin-right: 20px;
    }

    .px-form-item {
      margin-bottom: 0;
    }
  }

  .con_top {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 360px;
    margin-bottom: 16px;

    .con_top_item:nth-child(1) {
      width: 33%;
      margin-right: 16px;
    }

    .con_top_item:nth-child(2) {
      width: 67%;
    }
  }

  .con_bot {
    width: 100%;
  }

  .ffu_total {
    width: 100%;
    height: 100%;

    .iframe-con {
      box-sizing: border-box;
      width: 100%;
      height: 100%;
      overflow: hidden !important;
      border: 0;
    }
  }
}

.content-left {
  width: 310px;
  height: 100%;
  padding: 16px 24px;
  background: #fff;
  border-radius: 4px;

  .tree-title {
    padding: 8px 8px 0;
    font-size: 14px;
    font-weight: bold;
  }

  .tree-search {
    padding: 8px;
  }

  .tree-bar {
    width: 100%;
    height: calc(100vh - 222px);
    overflow-y: auto;
  }
}

.content-right {
  display: flex;
  flex: 1;
  flex-direction: column;
  height: 100%;
  padding-left: 16px;

  .content {
    position: relative;
    display: flex;
    flex: 1;

    .children-download {
      position: absolute;
      top: 0;
      right: 20px;
    }
  }
}

.tree-tab {
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 196px;
  height: 44px;
  margin-bottom: 24px;
  background: #f4f4f4;
  border-radius: 4px;

  .tree-tab-item {
    width: 60px;
    height: 36px;
    line-height: 36px;
    text-align: center;
    cursor: pointer;
  }

  .active-tab {
    color: #fff;
    background: #4089f7;
    border-radius: 4px;
    box-shadow: 0 2px 4px 0 #b5d2fe;
  }
}
</style>
